package com.tfswue.jqr.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(1)
//注入Spring容器
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 新增
        String path = exchange.getRequest().getPath().value();

        // 放行 Swagger 相关路径
        if (path.startsWith("/swagger-ui/") || path.startsWith("/v3/api-docs")) {
            return chain.filter(exchange);
        }

        // 1.获取请求参数
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        // 2.获取authorizetion参数
        String auth = params.getFirst("authorization");
        // 3.校验，往authorization中放入Token
        if ("admin".equals(auth)) {
            // 放行
            return chain.filter(exchange);  //测试，浏览器访问http://localhost:10086/api/users/1?authorization=admin
        }
        // 4.拦截
        // 4.1.禁止访问，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); //测试，浏览器访问http://localhost:10086/api/users/1被拦截
        // 4.2.结束处理
        return exchange.getResponse().setComplete();
    }
}
